import 'package:dio/dio.dart';
import 'package:jicaimao_flutter/config/config.dart';
import 'package:jicaimao_flutter/net/net_code.dart';
import 'package:jicaimao_flutter/utils/result_data.dart';
import 'package:connectivity/connectivity.dart';

class HttpManager {
  static const mConnectionTimeOut = 30 * 1000;
  static const mReceiveTimeOut = 3000;

  ///
  /// [url] 请求URL
  /// [params] 请求参数
  /// [option] 请求规则设置 请求方式
  /// [noTip]
  ///
  ///
  static netFetch(url, params, Map<String, String> header, Options option,
      {noTip = false}) async {
    var connectivityResult = await (Connectivity().checkConnectivity());
    if (connectivityResult == ConnectivityResult.none) {
      return ResultData(Code.errorHandleFunction(Code.NETWORK_ERROR, "", noTip),
          false, Code.NETWORK_ERROR);
    }
    Map<String, String> headers = Map();
    if (header != null) {
      header.addAll(header);
    }

   
    if (option != null) {
      option.headers = headers;
    } else {
      ///设置默认方式为 GET 请求方式
      option = Options(method: "get");
      option.headers = headers;
    }

    option.connectTimeout = mConnectionTimeOut;
    option.receiveTimeout = mReceiveTimeOut;

    Dio dio = Dio();
    Response response;

    try {
      response = await dio.request(url, data: params, options: option);
    } on DioError catch (e) {
      Response errorResponse;
      if (e.response != null) {
        errorResponse = e.response;
      } else {
        errorResponse = Response(statusCode: 666);
      }

      if (e.type == DioErrorType.CONNECT_TIMEOUT) {
        errorResponse.statusCode = Code.NETWORK_TIMEOUT;
      }

      if (Config.DEBUG) {
        print('请求异常:${e.message}');
        print('请求异常:${e.toString()}');
        print('请求异常url:$url');
      }

      return ResultData(
          Code.errorHandleFunction(errorResponse.statusCode, e.message, noTip),
          false,
          errorResponse.statusCode);
    }

    if (Config.DEBUG) {
      print('请求url: ' + url);
      print('请求头: ' + option.headers.toString());
      if (params != null) {
        print('请求参数: ' + params.toString());
      }
      if (response != null) {
        print('返回参数: ' + response.toString());
      }
    }
    try {
      if (option.contentType != null &&
          option.contentType.primaryType == 'text') {
        return ResultData(response.data, true, Code.SUCCESS);
      }

      if (response.statusCode == 200 || response.statusCode == 201) {
        return ResultData(response.data, true, Code.SUCCESS);
      }
    } catch (e) {
      print(e.toString() + url);
      return ResultData(
        response.data,
        false,
        response.statusCode,
      );
    }

    return ResultData(Code.errorHandleFunction(response.statusCode, "", noTip),
        false, response.statusCode);
  }
}
